package com.rskj.cashbook.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Configuration
public class SqlMonitorConfig {

    @Value("${sql.monitor.async.core-pool-size:2}")
    private int corePoolSize;

    @Value("${sql.monitor.async.max-pool-size:4}")
    private int maxPoolSize;

    @Value("${sql.monitor.async.queue-capacity:1000}")
    private int queueCapacity;

    @Value("${sql.monitor.async.keep-alive-seconds:60}")
    private int keepAliveSeconds;

    @Value("${sql.monitor.async.thread-name-prefix:sql-monitor-}")
    private String threadNamePrefix;

    @Bean("sqlMonitorExecutor")
    public Executor sqlMonitorExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix(threadNamePrefix);
        
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        
        executor.initialize();
        
        log.info("SQL监控异步线程池初始化完成: corePoolSize={}, maxPoolSize={}, queueCapacity={}", 
                corePoolSize, maxPoolSize, queueCapacity);
        
        return executor;
    }
}
